﻿using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI.WebControls;

using NCS.Library;
using NCS.Library.Components;
using NCS.Library.Components.Portal;
using NCS.Library.Components.Security;
using NCS.Library.Utilities;
using NCS.Module.CMS.Admin.UserControls;
using NCS.Module.CMS.Library.CMSPermisions;
using NCS.Module.CMS.Library.Contents;
using NCS.Module.CMS.Library.Definitions;
using NCS.Module.CMS.Library.Distributions;
using NCS.Module.CMS.Library.Zones;
using NCS.Module.CMS.Library.Events;
using NCS.Library.Components.Partner;
using NCS.Module.CMS.Library.Feed;

namespace NCS.Module.CMS.Admin.Author
{
	public partial class CreateContent : AuthenticatedControl
	{
		private bool isManager, isPublisher, isCreater;
		private string curDateString = DateTime.Now.Year.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Day.ToString();
        private string userUploadPath = Constants.UploadPath;
        private void CheckPath()
        {
            //FCKeditor1.Height = 200;
            //FCKeditor1.Width = 504;
            txtContent.Height = 300;
            //txtContent.Width = 750;

            //userUploadPath += CurrentUser.UserID;// +"/Nam_" + DateTime.Now.Year.ToString();
            string folder = userUploadPath;// +"/Thang_" + DateTime.Now.Month.ToString() + "/Ngay_" + DateTime.Now.Day.ToString();
            string avatarPath = folder + "/Avatar/";

            if (!Directory.Exists(Server.MapPath(folder)))
            {
                Directory.CreateDirectory(Server.MapPath(folder));
            }
            if (!Directory.Exists(Server.MapPath(avatarPath)))
            {
                Directory.CreateDirectory(Server.MapPath(avatarPath));
            }
       
        }

		protected void Page_Load(object sender, EventArgs e)
		{
            //Response.Write("nguyen quoc tuan");
            if (!IsPostBack)
            {
                txtContent.Language = "vi";
                CKFinder.FileBrowser _FileBrowser = new CKFinder.FileBrowser();
                _FileBrowser.BasePath = "/ckfinder/";
                _FileBrowser.SetupCKEditor(txtContent);

                if (NCS.Library.AppEnv.GetLanguage() == "vi-VN")
                {
                    txtDatetime.Text = DateTime.Now.ToString("dd/MM/yyyy") + " " + DateTime.Now.ToLongTimeString();
                }
                else
                {
                    txtDatetime.Text = DateTime.Now.ToString("MM/dd/yyyy") + " " + DateTime.Now.ToLongTimeString();
                }
            }
            
			lblUpdateStatus.Text = string.Empty;
            isManager = CMSPermisionController.CheckUserPermision(CurrentUser.UserID, (int)CMSPermision.Manager, ConvertUtility.ToInt32(AppEnv.PortalId()));
            isPublisher = CMSPermisionController.CheckUserPermision(CurrentUser.UserID, (int)CMSPermision.Publisher, ConvertUtility.ToInt32(AppEnv.PortalId()));
            isCreater = CMSPermisionController.CheckUserPermision(CurrentUser.UserID, (int)CMSPermision.Creater, ConvertUtility.ToInt32(AppEnv.PortalId()));

            //txtAvatar2Height.Text   = Constants.ThumbHeight.ToString();
            //txtAvatar2width.Text    = Constants.ThumbWidth.ToString();
            txtSpecialAvatarHeight.Text = Constants.ThumbSpecialHeight.ToString();
            txtSpecialAvatarwidth.Text = Constants.ThumbSpecialWidth.ToString();
            lblStatusUpdate.Text = string.Empty;

            if (isManager || isPublisher)
            {
                chkwaitting.Visible = true;
            }
            else if (isCreater)
            {
                chkwaitting.Visible = false;
            }
                      

			if (!IsPostBack)
			{
                CheckPath();  
                MiscUtility.FillIndex(dropExpireDay, 1, 31, 1);
                MiscUtility.FillIndex(dropExpireMonth, 1, 12, 1);
                MiscUtility.FillIndex(dropExpireYear, 2000, 2020, 2020);
                
                LoadZones();
            }

            
		}
       
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);  
            
            //txtTeaser.UploadDir = userUploadPath;
            //txtContent.UploadDir = userUploadPath;
            txtAvatar.fpUploadDir = userUploadPath;
            txtSpecialAvatar.fpUploadDir = userUploadPath;
            
            dropEvent.DataSource = EventController.GetAll();
            dropEvent.DataBind();
            dropEvent.Items.Insert(0, new ListItem("   ---- Chọn sự kiện ----", "0"));
            dropPartner.DataSource = PartnerController.GetPartners();
            dropPartner.DataBind();
            dropPartner.Items.Insert(0, new ListItem("   ---- Chọn đối tác ----", "0"));

            string feedcontentid = "";
            try
            {
                feedcontentid = Request.QueryString["feedcontentid"];
            }
            catch { }
            if (feedcontentid != "")
            {
                FeedContentInfo finfo = FeedContentController.GetFeedInfo(feedcontentid);
                if (finfo != null)
                {
                    txtHeadline.Text = finfo.Title;
                    //FCKeditor1.Value = finfo.Summary;
                    this.txt_teaser.Text = finfo.Summary;
                    txtContent.Text = finfo.Content;
                    txtAvatar.Text = finfo.Logo;
                    lbAlias.Text = finfo.Author;
                    chkAlbum.Checked = false;
                    txtSubTitle.Text = finfo.SubTitle;
                    txtNoteBox.Text = "";
                }
            }
        }
		private void LoadZones()
		{
			lstZones.Enabled = false;
			rdoContentRanks.Enabled = false;

            dropZones.Items.Clear();
            lstZones.Items.Clear();
            ZoneController.LoadZones(dropZones.Items, AppEnv.PortalId(), 0);
            dropZones.Items.Insert(0, new ListItem("Root", "0"));

			if(!isManager)
			{
                string permisionZoneCollection = CMSPermisionController.GetPermisionZones(CurrentUser.UserID, ConvertUtility.ToInt32(AppEnv.PortalId()));
				if (permisionZoneCollection != null && permisionZoneCollection.Length > 1)
				{
					int i = 0;
					while (i < dropZones.Items.Count)
					{
						if (permisionZoneCollection.IndexOf("|" + dropZones.Items[i].Value + "|") < 0)
						{
						    dropZones.Items.RemoveAt(i);
						}
						else
						{
						    i += 1;
						}
					}
				}
                else
				{
					dropZones.Items.Clear();
				}
			}
			if (isManager || isPublisher)
			{
				lstZones.Enabled = true;
				rdoContentRanks.Enabled = true;
			}
            
          
            foreach (ListItem item in dropZones.Items)
            {
                lstZones.Items.Add(new ListItem(item.Text, item.Value));
            }

		}
		private ContentInfo GetContent()
		{
			ContentInfo contentInfo = new ContentInfo();

            contentInfo.Content_Headline            = ConvertUtility.ToString(txtHeadline.Text);
            //contentInfo.Content_Teaser = MiscUtility.OptimiseContent(FCKeditor1.Value);
            contentInfo.Content_Teaser = MiscUtility.OptimiseContent(this.txt_teaser.Text);
            contentInfo.Content_Body = txtContent.Text; 
			contentInfo.Content_Avatar              = txtAvatar.Text;
			contentInfo.Content_AvatarDescription   = txtAvatarDes.Text;
			contentInfo.Content_AvatarWidth         = Constants.ThumbWidth;
            contentInfo.Content_AvaterHeight        = Constants.ThumbHeight;
			contentInfo.Content_ZoneID              = ConvertUtility.ToInt32(dropZones.SelectedValue);
			contentInfo.Content_UserID              = CurrentUser.UserID;
			contentInfo.Content_ModifiedUserID      = CurrentUser.UserID;
            contentInfo.Content_ApproveUser = 0;
            contentInfo.Content_IsComment           = chkIsComment.Checked;
            contentInfo.SpecialAvatar = txtSpecialAvatar.Text;
            MultimediaUtility.SetAvatarThumbnail(Server.MapPath(contentInfo.Content_Avatar), contentInfo.Content_AvatarWidth, 0);
            MultimediaUtility.SetAvatarListThumbnail(Server.MapPath(contentInfo.Content_Avatar), Constants.ThumbListWidth, 0);
            MultimediaUtility.SetAvatarSpecialThumbnail(Server.MapPath(contentInfo.SpecialAvatar), Constants.ThumbSpecialWidth, Constants.ThumbSpecialHeight);
		    contentInfo.Content_Alias               = lbAlias.Text;
		    contentInfo.Content_Source              = ConvertUtility.ToString(txtSource.Text);
            contentInfo.Content_AvatarSource = ConvertUtility.ToInt32(dropPartner.SelectedValue);
            contentInfo.Event_ID = ConvertUtility.ToInt32(dropEvent.SelectedValue);
            contentInfo.Content_SubTitle = txtSubTitle.Text;
            contentInfo.Content_NoteBox = txtNoteBox.Text;
            contentInfo.SetAlbum = chkAlbum.Checked;
			return contentInfo;
		}

        protected void cmdAdd_Click(object sender, EventArgs e)
        {
            ContentInfo info = GetContent();
            int contentid = 0;
            if (isManager || isPublisher)
            {
                try
                {
                    //Đăng bài với trạng thái chờ đăng (2)
                    if (chkwaitting.Checked)
                    {
                        try
                        {
                            info.Content_Status = (int)CMSWorkFlow.Waiting;
                            contentid = ContentController.AddContent(info);
                            lblUpdateStatus.Text = Constants.MSG_Waiting + dropZones.SelectedItem.Text;                            
                            cmdHuy_Click(null, null);
                        }
                        catch 
                        { 
                            lblStatusUpdate.Text = MiscUtility.MSG_UPDATE_ERROR;
                        }
                    }
                    //Đăng thẳng bài lên (4)
                    else
                    {
                        info.Content_Status = (int)CMSWorkFlow.Deploy;
                        int newContentID = ContentController.AddContent(info);
                        contentid = newContentID;
                        lblUpdateStatus.Text = Constants.MSG_Deploy + "<br>";
                        lstZones.Items.FindByValue(dropZones.SelectedValue).Selected = true;

                        foreach (ListItem item in lstZones.Items)
                        {
                            if (item.Selected)
                            {
                                int zoneID = ConvertUtility.ToInt32(item.Value);

                                DistributionInfo newDist = new DistributionInfo();

                                newDist.Distribution_ContentID  = newContentID;
                                newDist.Distribution_ZoneID     = zoneID;
                                newDist.Distribution_Rank       = Convert.ToInt32(rdoContentRanks.SelectedValue);
                                newDist.Distribution_ExpireDate = new DateTime(Convert.ToInt32(dropExpireYear.SelectedValue), Convert.ToInt32(dropExpireMonth.SelectedValue), Convert.ToInt32(dropExpireDay.SelectedValue));
                                newDist.Portal_ID = ConvertUtility.ToInt32(AppEnv.PortalId());

                                //int i1      = txtDatetime.Text.IndexOf("/");
                                //int l1      = txtDatetime.Text.Substring(0, i1).Length;
                                //string temp = txtDatetime.Text.Substring(i1 + 1);
                                //int i2      = temp.IndexOf("/");
                                //int l2      = temp.Substring(0, i2).Length;
                                //string time = txtDatetime.Text.Substring(l1 + 1, l2) + "/" +
                                //              txtDatetime.Text.Substring(0, l1) + "/" + temp.Substring(l2 + 1);
                                //string date = txtDatetime.Text;
                                //string day = date.Substring(0, date.IndexOf("/"));
                                //string month = date.Substring(date.IndexOf("/") + 1, 2);
                                //string year = date.Substring(date.LastIndexOf("/") + 1,4);
                                //string hour = date.Substring(date.IndexOf(" ")+1,date.IndexOf(":")-(date.IndexOf(" ")+1));
                                //string munite = date.Substring(date.IndexOf(":")+1,2);
                                //string second = date.Substring(date.LastIndexOf(":")+1,2);
                                
                                //DateTime newdate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), Convert.ToInt32(day)).AddHours(Convert.ToInt32(hour)).AddMinutes(Convert.ToInt32(munite)).AddSeconds(Convert.ToInt32(second));

                                //newDist.Distribution_WaittingDate = newdate; // ConvertUtility.ToDateTime(txtDatetime.Text);
                                
                                newDist.Distribution_WaittingDate = DateTime.Parse(txtDatetime.Text, new System.Globalization.CultureInfo(AppEnv.GetLanguage()));
                                newDist.Distribution_WaittingHour = ConvertUtility.ToInt32(txtHour.Text);
                                newDist.Distribution_View = 0;
                                newDist.HotNewsInHomePage = chkHotNews.Checked;
                                newDist.RightPositionInLevel2 = chkLevel2.Checked;

                                int distid = DistributionController.AddDistribution(newDist);
                                if (dropZones.SelectedValue == item.Value)
                                {
                                    if(ConvertUtility.ToInt32(dropEvent.SelectedValue)>0)
                                    {
                                      //  EventController.Event_AddDistribution(ConvertUtility.ToInt32(dropEvent.SelectedValue), distid);
                                        EventController.Event_AddDistribution(ConvertUtility.ToInt32(dropEvent.SelectedValue), newDist.Distribution_ContentID); 
                                    }
                                }
                                lblUpdateStatus.Text += item.Text + ",<br>";
                            }
                        }
                        
                    }
                    // Xoa Cache
                    if (chkCache.Checked)
                    {
                        DataTable dt = PortalCacheController.GetPortalCacheByPortalIdAndZoneID(ConvertUtility.ToInt32(AppEnv.PortalId()), ConvertUtility.ToInt32(dropZones.SelectedValue));
                        
                        HttpContext context = HttpContext.Current;
                        IEnumerator dcEnum = context.Cache.GetEnumerator();
                        DataCaching dc = new DataCaching();
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                dc.RemoveCache(ConvertUtility.ToString(dt.Rows[i]["CacheKey"]));
                            }
                        }
                        else
                            dc.RemoveAll();
                    }
                    
                    // End Xoa Cache
                    lblUpdateStatus.Text = lblUpdateStatus.Text.Substring(0, lblUpdateStatus.Text.Length - 5) + "</font>";
                    cmdHuy_Click(null, null);
                }
                catch
                {
                    lblStatusUpdate.Text = MiscUtility.MSG_UPDATE_ERROR;
                }
            }
            // Nếu quyền chỉ là biên tập viên (creater) thi bài sẽ được đăng vào mục chờ đăng
            else if (isCreater)
            {
                try
                {
                    info.Content_Status = (int)CMSWorkFlow.Waiting;
                    contentid = ContentController.AddContent(info);

                    lblUpdateStatus.Text = Constants.MSG_Waiting + dropZones.SelectedItem.Text;
                    cmdHuy_Click(null, null);
                }
                catch
                {
                    lblStatusUpdate.Text = MiscUtility.MSG_UPDATE_ERROR;
                }
            }

            if (chkAlbum.Checked && contentid > 0)
            {
                lblUpdateStatus.Text += "<br/> Bài viết đã được chọn có album, <a href=\"" + AppEnv.AdminUrlParams("picturelistforcontent") + "&contentid=" + contentid + " \">bấm vào đây chuyển đến trang tạo Album cho bài viết này.</a>";
                //Response.Redirect(AppEnv.AdminUrlParams("picturelist") + "&contentid=" + contentid);
            }

            this.AddLog("CMS", " try add contetn \"" + info.Content_Headline + "\" success");
        }

        protected void cmdHuy_Click(object sender, EventArgs e)
        {
            txtHeadline.Text        = string.Empty;
            txtAvatar.Text          = string.Empty;
            txtSubTitle.Text = string.Empty;
            //txtAvatar2.Text         = string.Empty;
            txtAvatarDes.Text = string.Empty;
            lbAlias.Text = string.Empty;
            //FCKeditor1.Value = string.Empty;
            this.txt_teaser.Text = string.Empty;
            txtContent.Text    = string.Empty;
            foreach (ListItem item in lstZones.Items)
            {
                item.Selected = false;
            }
        }

        protected void cmdSave_Click(object sender, EventArgs e)
        {
            ContentInfo info = GetContent();

            info.Content_Status = (int)CMSWorkFlow.Archive;
            ContentController.AddContent(info);
            lblUpdateStatus.Text = Constants.MSG_Archive + dropZones.SelectedItem.Text;
            cmdHuy_Click(null, null);
            this.AddLog("CMS", " try add contetn \"" + info.Content_Headline + "\" success");
        }

        protected void cmdBack_Click(object sender, EventArgs e)
        {
            Response.Redirect(AppEnv.AdminUrlParams("cms_distributedlist"));
        }               
		
	}
}